import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Button, Form, Input, message, Modal, notification, Select } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

import Api from '@/apis/api';
import { Logger } from '@/components/useLogger';

import styles from '../styles.module.less';

const DeviceCheckButton: React.FC = () => {
  const queryClient = useQueryClient();
  const [api, contextHolder] = notification.useNotification();
  const [checkCycle, setCheckCycle] = useState<number>(0);
  const [visible, setVisible] = React.useState(false);

  const [form] = Form.useForm();

  // 获取当前自检周期
  const { data: checkCycleData } = useQuery({
    queryKey: ['getCheckCycle'],
    queryFn: async () => {
      const res: any = await Api.GetCheckCycle();
      return res.data;
    },
    enabled: !!visible,
  });
  // 获取上次自检时间
  const { data: checkTimeData } = useQuery({
    queryKey: ['getCheckTime'],
    queryFn: async () => {
      const res: any = await Api.GetCheckTime();
      return res.data;
    },
    enabled: !!visible,
  });

  const ChangeCheckCycle = useMutation({
    mutationFn: (params: any) => Api.ChangeCheckCycle(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('修改成功');
      } else {
        message.error(`修改失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('修改失败');
    },
  });

  const DeviceCheck = useMutation({
    mutationFn: () => Api.DeviceCheck(),
    onSuccess: (res: any) => {
      if (res?.success) {
        messageFunc();
      } else {
        message.error(`设备自检失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('设备自检失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getCheckTime'] }),
    mutationKey: ['getCheckTime'],
  });
  // 手动自检
  const onHandleCheck = () => {
    message.loading({ content: '设备自检中...', key: 'deviceCheck' });
    DeviceCheck.mutate();
  };

  // 修改自检周期
  const handleChangeCycle = () => {
    ChangeCheckCycle.mutate({
      interval: checkCycle,
    });
  };

  useEffect(() => {
    if (visible && checkCycleData) {
      form.setFieldsValue({ checkCycle: checkCycleData?.interval });
    }
    if (visible && checkTimeData) {
      form.setFieldsValue({
        lastCheckTime: checkTimeData?.test_time
          ? dayjs(checkTimeData?.test_time).format('YYYY-MM-DD HH:mm:ss')
          : '暂无',
      });
    }
  }, [checkCycleData, checkTimeData, form, visible]);

  const messageFunc = () => {
    api['info']({
      message: '设备自检',
      key: 'deviceCheck',
      description: (
        <>
          <div>算法正确性自检成功.</div>
          <div>固件完整性自检成功.</div>
          <div>随机数自检成功.</div>
          <p style={{ color: 'green' }}>设备自检成功!</p>
        </>
      ),
      duration: 2,
      placement: 'top',
    });
  };

  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    setVisible(false);
  };
  return (
    <>
      <div className={styles.InitializationButton1}>
        {contextHolder}
        <Button
          type="default"
          className={styles.Button}
          onClick={() => setVisible(true)}
          // disabled={LocalInfo.getRoleId() === 2}
        >
          设备自检
        </Button>
      </div>
      <Modal title="设备自检配置" open={visible} onCancel={handleCancel} footer={[]}>
        <Form form={form} style={{ maxWidth: 600, margin: 24 }}>
          <Form.Item
            label="自检周期"
            name="checkCycle"
            style={{ display: 'inline-block' }}
          >
            <Select
              placeholder="请选择自检周期"
              style={{ width: 160 }}
              allowClear
              onChange={(value) => {
                setCheckCycle(value);
              }}
              options={[
                { value: 3600, label: '1h' },
                { value: 7200, label: '2h' },
                { value: 14400, label: '4h' },
                { value: 28800, label: '8h' },
                { value: 43200, label: '12h' },
              ]}
            />
          </Form.Item>

          <Button
            type="primary"
            onClick={handleChangeCycle}
            style={{ marginLeft: 16 }}
            // disabled={localINFO.getRoleId() !== 1}
          >
            修改
          </Button>

          <Form.Item
            label="上次自检时间"
            name="lastCheckTime"
            style={{ display: 'inline-block' }}
          >
            <Input type="primary" style={{ width: 150 }} />
          </Form.Item>

          <Button
            type="primary"
            onClick={onHandleCheck}
            style={{ marginLeft: 16 }}
            // disabled={localINFO.getRoleId() !== 1}
          >
            手动自检
          </Button>
        </Form>
      </Modal>
    </>
  );
};

export default React.memo(DeviceCheckButton);
